package com.kevin.ymqquan.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;

import com.kevin.ymqquan.R;
import com.kevin.ymqquan.adapter.CourseListAdapter;
import com.kevin.ymqquan.adapter.MyClubListAdapter;
import com.kevin.ymqquan.application.App;
import com.kevin.ymqquan.bean.ClubListData;
import com.kevin.ymqquan.bean.CoachCourseList;
import com.kevin.ymqquan.constants.Constants;
import com.kevin.ymqquan.custom.CustomToast;
import com.kevin.ymqquan.httppost.Helper;
import com.kevin.ymqquan.httppost.HttpPostService;
import com.kevin.ymqquan.view.CommonListView;
import com.kevin.ymqquan.view.CommonListView.IXListViewListener;

public class MyCourseActivity extends Activity implements IXListViewListener,
		OnItemClickListener {

	private ImageView iv_my_club_back;

	private App application;
	private boolean isRefresh = false;
	private Dialog dialog;
	private List<CoachCourseList> myClubList = new ArrayList<CoachCourseList>();
	private int currPage = 1;
	// private String coachId;

	private CommonListView lv_myclub_list;

	CourseListAdapter myClubAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_coach_course);

		Intent i = getIntent();

		// coachId = i.getStringExtra("coachId");

		init();

		if (Helper.checkConnection(MyCourseActivity.this)) {
			dialog = CustomToast.createLoadingDialog(MyCourseActivity.this,
					"数据获取中...");
			dialog.setCancelable(true);
			dialog.show();
			MyClubAsynTask policyTask = new MyClubAsynTask(true);
			policyTask.execute();

		} else {
			CustomToast.CustomActivityToast(MyCourseActivity.this,
					"网络连接异常，请检查您的网络", -80);
		}
	}

	private void init() {
		// TODO Auto-generated method stub

		application = (App) getApplication();
		lv_myclub_list = (CommonListView) findViewById(R.id.lv_coach_course_list);
		iv_my_club_back = (ImageView) findViewById(R.id.iv_coach_course_back);

		// 下拉刷新不可用
		lv_myclub_list.setPullLoadEnable(true);
		lv_myclub_list.setPullRefreshEnable(true);
		lv_myclub_list.setXListViewListener(this);
		lv_myclub_list.stopLoadMore();
		lv_myclub_list.stopRefresh();

		myClubAdapter = new CourseListAdapter(MyCourseActivity.this, myClubList);
		lv_myclub_list.setAdapter(myClubAdapter);
		lv_myclub_list.setOnItemClickListener(MyCourseActivity.this);

		iv_my_club_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub\
				MyCourseActivity.this.finish();
			}
		});

	}

	@Override
	public void onRefresh() {
		// clearList();
		currPage = 1;
		isRefresh = true;
		MyClubAsynTask policyTask = new MyClubAsynTask(false);
		policyTask.execute();

	}

	@Override
	public void onLoadMore() {
		isRefresh = false;
		++currPage;
		MyClubAsynTask policyTask = new MyClubAsynTask(false);
		policyTask.execute();
	}

	public void clearList() {
		currPage = 1;
		myClubList.clear();
		myClubAdapter.notifyDataSetChanged();

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub

		if (position != 0) {
			Intent i = new Intent(MyCourseActivity.this,
					MyCourseDetailActivity.class);
			position--;
			i.putExtra("courseId", myClubList.get(position).getCourseId() + "");
			i.putExtra("courseName", myClubList.get(position).getCourseName());
			i.putExtra("coachName", myClubList.get(position).getCoachName());
			i.putExtra("type", myClubList.get(position).getType());
			i.putExtra("time", myClubList.get(position).getTime());
			i.putExtra("rs", myClubList.get(position).getRs());
			i.putExtra("price", myClubList.get(position).getPrice());

			i.putExtra("position", position + "");
//			startActivityForResult(i, position);
			 startActivity(i);
		}

	}
//
//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		// TODO Auto-generated method stub
//		// super.onActivityResult(requestCode, resultCode, data);
//		myClubList.get(requestCode).setIsJoin(resultCode + "");
//		Log.i("kevinlog", requestCode + "----" + resultCode);
//	}

	class MyClubAsynTask extends AsyncTask<String, Object, String> {

		private boolean dialogShow = true;

		public MyClubAsynTask(boolean dialogShow) {
			// TODO Auto-generated constructor stub
			this.dialogShow = dialogShow;
		}

		@Override
		protected String doInBackground(String... params) {

			String param = "{\"method\":\"myCourseList\",\"userId\":\""
					+ application.userId + "\",\"pageNum\":\"" + currPage
					+ "\"}";

			String replyList = "";
			try {
				replyList = HttpPostService.PostJsonString(
						Constants.ServerAddr, param);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Log.i("kevinlog", "--++--" + param);
			Log.i("kevinlog", "--++--" + replyList);
			return replyList;
		}

		@Override
		protected void onPostExecute(String JsonResult) {
			// TODO Auto-generated method stub
			super.onPostExecute(JsonResult);
			// Log.i("sssss", JsonResult);
			if (JsonResult != null) {
				// String result = JsonResult.replace("\n", "");
				String result = JsonResult;
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(result);
					String resultType = jsonObject.getString("status");
					if ("0".equals(resultType)) {
						JSONArray jsonArray = jsonObject
								.getJSONArray("courseList");

						if (isRefresh) {
							myClubList.clear();
						}

						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject eduPolicyObject = jsonArray
									.getJSONObject(i);
							CoachCourseList eduPolicy = new CoachCourseList();
							eduPolicy.setCourseId(eduPolicyObject
									.getString("courseId"));
							eduPolicy.setCourseLogoUrl(eduPolicyObject
									.getString("courseLogoUrl"));
							eduPolicy.setCoachName(eduPolicyObject
									.getString("coachName"));
							eduPolicy.setCourseName(eduPolicyObject
									.getString("courseName"));
//							eduPolicy.setIsJoin(eduPolicyObject
//									.getString("isJoin"));
							eduPolicy.setPrice(eduPolicyObject
									.getString("price"));
							eduPolicy.setRs(eduPolicyObject.getString("rs"));

							eduPolicy
									.setType(eduPolicyObject.getString("type"));
//							eduPolicy.setIsOver(eduPolicyObject
//									.getString("isOver"));
							eduPolicy
									.setTime(eduPolicyObject.getString("time"));
							// if (!clubList.contains(eduPolicy))
							myClubList.add(eduPolicy);
						}

						myClubAdapter.notifyDataSetChanged();

						if (dialogShow) {
							dialog.dismiss();
						}
					} else {
						if (dialogShow) {
							dialog.dismiss();
						}
						CustomToast.CustomActivityToast(MyCourseActivity.this,
								"没有更多了", -80);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					if (dialogShow) {
						dialog.dismiss();
					}
					CustomToast.CustomActivityToast(MyCourseActivity.this,
							"没有更多了", -80);
					e.printStackTrace();
				}

				lv_myclub_list.stopLoadMore();
				lv_myclub_list.stopRefresh();
			} else {
				if (dialogShow) {
					dialog.dismiss();
				}
				CustomToast.CustomActivityToast(MyCourseActivity.this,
						"网络异常请稍后重试！", -80);

			}
		}
	}

}
